﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson;

namespace MongoDBDemo
{
    class Program
    {
        /*
         * MongoDB版本：3.2.8
         * C# Driver版本：2.2.4
         */
        public static MongoClient client = new MongoClient("mongodb://172.0.0.104");
        public static IMongoDatabase database = client.GetDatabase("demo");
        static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                database.GetCollection<Student>("student").Database.DropCollection("student");

                #region 插入一条
                Console.WriteLine("插入一条");
                await database.GetCollection<Student>("student").InsertOneAsync(new Student { UserName = "第1条", Sex = 1, CreateDate = DateTime.Parse("2000-1-1") });
                Show();
                #endregion

                #region 插入多条
                Console.WriteLine("插入多条");
                var list = new List<Student>
                {
                    new Student { UserName = "第2条", Sex = 1 },
                    new Student { UserName = "第3条", Sex = 2 },
                    new Student { UserName = "第4条", Sex = 2 },
                };
                await database.GetCollection<Student>("student").InsertManyAsync(list);
                Show();
                #endregion

                #region 更新一条
                Console.WriteLine("更新一条");
                await database.GetCollection<Student>("student").UpdateOneAsync(x => x.UserName.Equals("第2条"),
                    Builders<Student>.Update.Set(x => x.UserName, "第2条 update")
                                            .AddToSet(x => x.Comments, "第2条 Comments 2")
                                            .AddToSet(x => x.Comments, "第2条 Comments 3"));
                Show();
                #endregion

                #region 更新多条
                Console.WriteLine("更新多条");
                await database.GetCollection<Student>("student").UpdateManyAsync(x => x.Sex == 2,
                    Builders<Student>.Update.Set(x => x.UserName, "被更新了"));
                Show();
                #endregion

                #region 删除一条
                Console.WriteLine("删除一条");
                await database.GetCollection<Student>("student").DeleteOneAsync(x => x.UserName.Equals("第1条"));
                Show();
                #endregion

                #region 删除多条
                Console.WriteLine("删除多条");
                await database.GetCollection<Student>("student").DeleteManyAsync(x => x.CreateDate > DateTime.Parse("2000-1-1"));
                Show();
                #endregion

                await InitData();

                #region 查询一条
                Console.WriteLine("查询一条");
                var model = await database.GetCollection<Student>("student").Find(x => x.UserName == "姓名200").FirstOrDefaultAsync();
                Console.WriteLine(model.ToString());
                Console.WriteLine("");
                #endregion

                #region 查询日期大于2015年的
                Console.WriteLine("查询日期大于2015年的");
                var manyList = await database.GetCollection<Student>("student").Find(x => x.CreateDate > DateTime.Parse("2015-1-1")).ToListAsync();
                foreach (var item in manyList)
                {
                    Console.WriteLine(item.ToString());
                }
                Console.WriteLine("");
                #endregion

                #region 统计日期大于2018年的
                Console.WriteLine("统计日期大于2018年的");
                var count = await database.GetCollection<Student>("student").CountAsync(x => x.CreateDate > DateTime.Parse("2018-1-1"));
                Console.WriteLine("共{0}条", count);
                Console.WriteLine("");
                #endregion

                #region 查询排序分页(第二页)
                Console.WriteLine("查询排序分页(第二页)");
                int pageIndex = 2;
                int pageSize = 10;
                var queryList = await database.GetCollection<Student>("student").Find(x => x.UserName.Contains("姓名2"))
                                                                                .SortByDescending(x => x.CreateDate)
                                                                                .Skip((pageIndex - 1) * pageSize)
                                                                                .Limit(pageSize)
                                                                                .ToListAsync();
                foreach (var item in queryList)
                {
                    Console.WriteLine(item.ToString());
                }
                Console.WriteLine("");
                #endregion


            }).Wait();

            Console.Read();
        }

        public static void Show()
        {
            var all = database.GetCollection<Student>("student").Find(Builders<Student>.Filter.Empty).ToList();
            foreach(var item in all)
            {
                Console.WriteLine(item.ToString());
            }
            Console.WriteLine("");
        }

        public static async Task InitData()
        {
            Random random = new Random();
            var list = new List<Student>();
            for(int i = 0; i < 500; i++)
            {
                list.Add(new Student
                {
                    UserName = "姓名" + i.ToString(),
                    Sex = random.Next(1, 3),
                    CreateDate = DateTime.Parse(string.Format("{0}-1-1", random.Next(1990, 2020))),
                    Comments = new List<string> { i.ToString() },
                });
            }
            await database.GetCollection<Student>("student").InsertManyAsync(list);
        }
    }
}
